<?php
namespace Admin\Controller;
use Admin\Controller\CheckController;
use Admin\Controller\CarController;

class MatApplyController extends AdminController
{
    //垫资管理
    protected function _initialize()
    {
        parent::_initialize();
    }

    public function index()
    {
        $where = '1 = 1';
        if (I('get.aid', -1, 'intval') <> -1) {
            if (I('get.aid', -1, 'intval') == 0) {
                $where .= ' and  aid =0';
            } else {
                $where .= ' and aid=' . I('get.aid', 0, 'intval');
            }
        }
        $where .= I('get.user_name') != '' ? ' and user_name like "%' . I('get.user_name') . '%"' : '';

        $where .= I('get.telephone') != '' ? ' and telephone = ' . I('get.telephone') : '';

        $where .= I('get.create_time_beg') != '' ? ' and create_time >= ' . strtotime(I('get.create_time_beg')) : '';

        $where .= I('get.create_time_end') != '' ? ' and create_time < ' . strtotime(I('get.create_time_end')) : '';
        $where .= ' and (check_status=6 and u.status!=101 )or (check_status=6 and u.status!=101 and a.status=0)';
        if (session('adminInfo.gpid') != 0) {
            $groupInfo = $this->getInfo('*', 'group', 'id=' . session('adminInfo.gpid'));
            if ($groupInfo['work_status'] == 1) {
                $where .= ' and gpid=' . session('adminInfo.gpid');
            }
        }
//        if($this->getInfo('*','advance','user_id'=))
        $arr = $this->getList('u.*,b.bank_short_name', 'user u', $where, '', true, 'left join app_bank b on u.loan_bank_id=b.id left join app_advance a on a.user_id=u.id');
//        var_dump($where);die;
        foreach ($arr as $key => $value) {
            $group = $this->getInfo('*', 'group', 'id=' . $value['gpid']);
            // $list[$key]['group_name']=$group['name'];
            $mat_apply = $this->getInfo('*', 'advance', 'user_id=' . $value['id']);
            if (!$mat_apply) {
                $arr[$key]['id'] = $value['id'];
                $arr[$key]['entry_no'] = $value['entry_no'];
                $arr[$key]['user_name'] = $value['user_name'];
                $arr[$key]['identity_no'] = $value['identity_no'];
                $arr[$key]['telephone'] = $value['telephone'];
                $arr[$key]['group_name'] = $group['name'];
                $arr[$key]['bank_short_name'] = $value['bank_short_name'];
                $arr[$key]['create_time'] = $value['create_time'];
                $arr[$key]['update_time'] = $value['update_time'];
                $arr[$key]['matStatus'] = $mat_apply['status'];
            }
        }
//		print_r($arr);die;
        $this->assign('list', $arr);
        $this->display();
    }

    public function add()
    {
        $id = I('get.user_id', 0, 'intval');
//		print_r($id);die;
        $bankList = $this->getList('*', 'bank', 'status=1');
        $groupInfo = $this->getInfo('*', 'group', 'id=' . session('adminInfo.gpid'));
        if ($groupInfo['work_status'] == 1) {
            $payee = $this->getList('*', 'payee', 'status=1 and gid=' . session('adminInfo.gpid'));
        } else {
            $payee = $this->getList('*', 'payee', 'status=1');
        }
        // $payee=$this->getList('*','payee','status=1 and gid='.session('adminInfo.gpid'));
        $info = $this->getInfo('*', 'user', 'id=' . $id);
        $this->assign('info', $info);
        $this->assign('payee', $payee);
        $this->assign('bank', $bankList);
        $this->display();
    }

    public function edit()
    {
        if (IS_POST) {
            $payee = $this->getInfo('*', 'payee', 'id=' . $_POST['payee_id']);
            $data = array(
                'admin_id' => session('adminInfo.id'),//业务员id
                'user_id' => $_POST['user_id'],//申请人id
                'pay_id' => $_POST['payee_id'],//收款单位id
                'bank_name' => $payee['bank_name'],//开户银行
                'user_name' => session('adminInfo.name'),//申请人
                'bank_card' => $payee['bank_card'],//账号
                'add_time' => strtotime($_POST['add_time']),//垫资申请时间
                'apply_time' => strtotime(date('Y-m-d H:i:s')),
                'status' => 1,
            );
            if ($_POST['mat_id'] != '') {
                $result = M('advance')->where('id=' . $_POST['mat_id'])->save($data);
            } else {
                $info = $this->getInfo('*', 'advance', 'user_id=' . $_POST['user_id']);
                if ($info && $info['status'] != 0) {
                    $this->error('该申请人垫资信息已录入', U('MatApply/index'));
                } elseif ($info != '' && $info['status'] == 0) {
                    $result = M('advance')->where('user_id=' . $_POST['user_id'])->setField($data);
                } else {
                    $result = M('advance')->add($data);
                }
            }
            if ($result  !==   false) {
                $log = array('user_id' => $_POST['user_id'], 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'type' => session('adminInfo.group_name'), 'check_status' => 7,
                    'status' => 2, 'opinion' => '垫资申请已提交', 'note' => '垫资申请已提交', 'add_time' => time());
                $result = M('check_log')->add($log);
                $apply = array('status' => '1','check_status'=>7, 'check_admin_id' => session('adminInfo.id'));
                M('user')->where('id=' . $_POST['user_id'])->setField($apply);
                $this->success('垫资申请修改成功', U('MatApply/index'));
            } else {
                $this->error('垫资申请修改失败', U('MatApply/index'));
            }
        } else {
            $user_id = I('get.user_id', 0, 'intval');
            //垫资信息
            $advanceInfo = $this->getInfo('*', 'advance_info', 'user_id = ' . $user_id);
            $bankList = $this->getList('*', 'bank', 'status=1');
            if (session('adminInfo.gpid') != 0) {
                $payee = $this->getList('*', 'payee', 'status=1 and gid=' . session('adminInfo.gpid'));
            } else {
                $payee = $this->getList('*', 'payee', 'status=1');
            }
            $info = $this->getInfo('m.id as mat_id,m.bank_card,m.bank_name,m.pay_id,m.add_time,u.*', array('user u', 'advance m'), 'u.id=m.user_id and m.user_id=' . $user_id);
            $this->assign('advanceInfo', $advanceInfo);
            $this->assign('info', $info);
            $this->assign('payee', $payee);
            $this->assign('bank', $bankList);
            $this->display('add');
        }
    }

    //垫资待审核(已添加申请待审核)
    public function wait_check()
    {
        $list = $this->getMatApply_status(1);
        $this->assign('list', $list);
        $this->display();
    }

    //垫资待打款
    //
    public function wait_pay()
    {
        $list = $this->getMatApply_status(2);
        $this->assign('list', $list);
        $this->display();
    }

    //垫资未通过
    public function Returns()
    {
        $list = $this->getMatApply_status(9);
        $this->assign('list', $list);
        $this->display();
    }

    //垫资资料补录列表
    public function add_info()
    {
        $where = '1 = 1';
        $where .= ' and u.id=m.user_id and u.check_status=9 and m.status=3';
        if (session('adminInfo.gpid') != 0) {
            $groupInfo = $this->getInfo('*', 'group', 'id=' . session('adminInfo.gpid'));
            if ($groupInfo['work_status'] == 1) {
                $where .= ' and gpid=' . session('adminInfo.gpid');
            }
        }
//		print_r($where);die;
        //       if(session('adminInfo.gpid')!=0){
        //            $where.=' and gpid='.session('adminInfo.gpid');
        // }
        $list = $this->getList('m.id as mat_id,m.bank_card,m.bank_name,m.pay_id,m.add_time,m.status as mat_status,u.*,b.bank_short_name', 'user u', $where, 'id desc', true, 'join app_advance m on u.id=m.user_id left join  app_bank b on u.loan_bank_id=b.id');
        foreach ($list as $key => $value) {
            $group = $this->getInfo('*', 'group', 'id=' . $value['gpid']);
            $list[$key]['group_name'] = $group['name'];
        }
        $this->assign('list', $list);
        $this->display();
    }

    //垫资资料补录
    public function addInfo_second()
    {
        if (IS_POST)
        {
            $user_id = I('post.user_id', 0, 'intval');
            $userInfo = $this->getInfo('*', 'user', 'id=' . $user_id . ' and check_status=9');
            if (!$userInfo)
            {
                $this->error('垫资资料已补录，不在该操作列表中', U('MatApply/add_info'), 0);
            }

            $_POST = array(
                'vin'                => $_POST['vin'],
                'chassis_number_six' => $_POST['six'],
                'engine_no'          => $_POST['engine_no'],
            );

            include VENDOR_PATH . 'aliyunOss/autoload.php';

            if($_FILES['frist_voucher_img']['tmp_name'] != '')
            {
                $_POST['frist_voucher_img'] = $this->uploadAliyunOss('frist_voucher_img');
            }

            if($_FILES['bill_img']['tmp_name'] != '')
            {
                $_POST['bill_img'] = $this->uploadAliyunOss('bill_img');
            }

            if($_FILES['warranty_img']['tmp_name'] != '')
            {
                $_POST['warranty_img'] = $this->uploadAliyunOss('warranty_img');
            }

            if($_FILES['warranty2_img']['tmp_name'] != '')
            {
                $_POST['warranty2_img'] = $this->uploadAliyunOss('warranty2_img');
            }

            if($_FILES['certificate_img']['tmp_name'] != '')
            {
                $_POST['certificate_img'] = $this->uploadAliyunOss('certificate_img');
            }

            if($_FILES['registration_img']['tmp_name'] != '')
            {
                $_POST['registration_img'] = $this->uploadAliyunOss('registration_img');
            }

            if($_FILES['warranty3_img']['tmp_name'] != '')
            {
                $_POST['warranty3_img'] = $this->uploadAliyunOss('warranty3_img');
            }

            if($_FILES['warranty4_img']['tmp_name'] != '')
            {
                $_POST['warranty4_img'] = $this->uploadAliyunOss('warranty4_img');
            }

            //补录的添加到垫资详情表
            $result = M('advance_info')->where('user_id=' . $user_id)->save($_POST);

            if ($result) {
                $apply = array('check_admin_id' => session('adminInfo.id'), 'check_status' => 10);
                M('user')->where('id=' . $user_id)->save($apply);
                //修改垫资状态
                $matApply = M('advance')->where('user_id=' . $user_id)->setField('status', 4);
                //增加补录记录
                $log = array('user_id' => $user_id, 'admin_id' => session('adminInfo.id'), 'admin_name' => session('adminInfo.name'), 'type' => session('adminInfo.group_name'), 'status' => 4, 'opinion' => '垫资已补录', 'note' => '垫资已补录', 'add_time' => time(), 'check_status' => 10);
                M('check_log')->add($log);
                redirect('/Admin/MatApply/add_info');
            } else {

                M('user')->where('id=' . $_POST['user_id'])->setField('status', 1);
                $this->error('补录失败,查看是否填写垫资资料', 0);
            }
        } else {
            $carInfo     = $this->getInfo('*','car_info','user_id= ' .I('get.user_id', 0,'intval'));
            $advanceInfo = $this->getInfo('*', 'advance_info', 'user_id=' . I('get.user_id', 0, 'intval'));
            $this->assign('info', $advanceInfo);
            $this->assign('carInfo', $carInfo);
            $this->display();
        }

    }

    //获得垫资审核状态
    public function getMatApply_status($status)
    {
        $where = '1 = 1';
        if (I('get.aid', -1, 'intval') <> -1) {
            if (I('get.aid', -1, 'intval') == 0) {
                $where .= ' and  u.aid =0';
            } else {
                $where .= ' and aid=' . I('get.aid', 0, 'intval');
            }
        }
        $where .= I('get.user_name') != '' ? ' and u.user_name like "%' . I('get.user_name') . '%"' : '';

        $where .= I('get.telephone') != '' ? ' and u.telephone = ' . I('get.telephone') : '';

        $where .= I('get.create_time_beg') != '' ? ' and u.create_time >= ' . strtotime(I('get.create_time_beg')) : '';

        $where .= I('get.create_time_end') != '' ? ' and u.create_time < ' . strtotime(I('get.create_time_end')) : '';
        $where .= ' and u.check_status=7  and m.status=' . $status.' and u.status!=101';
        $groupInfo = $this->getInfo('*', 'group', 'id=' . session('adminInfo.gpid'));
        if ($groupInfo['work_status'] == 1) {
            $where .= ' and gpid=' . session('adminInfo.gpid');
        }
        //       if(session('adminInfo.gpid')!=0){
        //            $where.=' and gpid='.session('adminInfo.gpid');
        // }
//        m.single_date,m.single_img,
        $list = $this->getList('m.id as mat_id,m.bank_card,m.bank_name,m.pay_id,m.add_time,m.status as mat_status,u.*,b.bank_short_name', 'user u', $where, 'id desc', true, 'join app_advance m on u.id=m.user_id left join  app_bank b on u.loan_bank_id=b.id');
        foreach ($list as $key => $value) {
            $group = $this->getInfo('*', 'group', 'id=' . $value['gpid']);
            $list[$key]['group_name'] = $group['name'];
        }
        return $list;
    }


    //收款单位详情
    public function payeeInfo()
    {
        $info = $this->getInfo('*', 'payee', 'id=' . $_POST['pay_id']);
        $info['user_name'] = session('adminInfo.name');
        $this->returnResult($info, null, null, $info);
    }

    public function import_advance()
    {
        if (IS_POST) {
            set_time_limit(0);
            ignore_user_abort(true);//检测用户断开
            if (!empty ($_FILES ['photo'] ['name'])) {
                $tmp_file = $_FILES ['photo'] ['tmp_name'];
                $file_types = explode(".", $_FILES ['photo'] ['name']);
                $file_type = $file_types [count($file_types) - 1];
                /*判别是不是.xls文件，判别是不是excel文件*/
                if ($file_type !== "xls") {
                    $this->error('不是Excel文件，重新上传');
                }
                $savePath = './Uploads/excel/';
                $str = date('Ymdhis');
                $file_name = $str . "." . $file_type;
                if (!move_uploaded_file($_FILES['photo']['tmp_name'], $savePath . $file_name)) {
                    $this->error('上传失败！');
                }
                $read = new CarController();
                $res = $read->read($savePath . $file_name);
                unset($res[1]);
            } else {
                $this->error('附件不能为空！');
            }
            $tems = 0;
            foreach ($res as $k => $v) {
                $user = $this->getInfo('*', 'user', 'identity_no=' . $v[1]);
                if (!$user) {
                    $this->error('该用户不存在');
                } else if ($user['check_status'] != 6 && $user['status'] != 0) {
                    $this->error('垫资申请状态条件不符合!!!!');
                } else {


                }
                $tems++;
            }
            $this->success("批量执行成功了：" . $tems . "条");
        } else {
            $this->display();
        }
    }
}